"""
结合数据库相关数据处理工具类
"""
import pandas as pd

def up_price(db, ali):
    """
    计算N日上浮成本
    N目前支持3，5，10
    :param db:
    :param ali:
    :return:
    """
    pd_bonds_alive_calc = pd.read_sql_table('JSL_bonds_alive_calc', con=db.engine)
    del pd_bonds_alive_calc['bond_nm']
    pd_bonds_alive_calc_rlt = pd.merge(ali, pd_bonds_alive_calc, how='left', on='bond_id')
    # print(pd_bonds_alive_calc_rlt)
    pd_bonds_alive_calc_rlt['up_price_3'] = round(pd_bonds_alive_calc_rlt['price'] -
                                                  pd_bonds_alive_calc_rlt['days_min_3'], 3)
    pd_bonds_alive_calc_rlt['up_price_5'] = round(pd_bonds_alive_calc_rlt['price'] -
                                                  pd_bonds_alive_calc_rlt['days_min_5'], 3)
    pd_bonds_alive_calc_rlt['up_price_10'] = round(pd_bonds_alive_calc_rlt['price'] -
                                                  pd_bonds_alive_calc_rlt['days_min_10'], 3)
    return pd_bonds_alive_calc_rlt

def adjust_compare_bond_hold_in(db, pd_adjust):
    """
    对比持仓信息和下修信息
    ver1 保留原有逻辑了 持仓的有*
    :return:
    """
    pd_hold_bonds = pd.read_sql_table('hold_info', con=db.engine)
    pd_hold_bonds = pd_hold_bonds[['证券名称']]
    pd_adjust['hold'] = pd_adjust['bond_nm'].isin(pd_hold_bonds['证券名称'])
    pd_adjust['hold'].replace(True, '*', inplace=True)
    pd_adjust['hold'].replace(False, '', inplace=True)
    return pd_adjust


def adjust_condition_concat(pd_adjust):
    """
    拼接下修要求信息 类似90% 15
    :param db:
    :param pd_adjust:
    :return:
    """
    pd_adjust['adjust_condition'] = pd_adjust['adjust_price_ratio'].astype(str) + '%-' + pd_adjust['adjust_count_days'].astype(str)
    return pd_adjust


def adjust_recent_arrive(pd_adjust):
    """
    下修计数快足够

    :param pd_adjust:
    :return:
    """
    will_adjust_count_enough = pd_adjust.loc[(pd_adjust['adjust_remain_days'] <= 3) &
                                             (pd_adjust['adjust_remain_days'] > 0)]
    will_adjust_count_enough = will_adjust_count_enough.sort_values('adjust_remain_days')

    return will_adjust_count_enough


def adjust_count_will_recount(pd_adjust):
    """
    近期下修计数快要重新开始的
    :param pd_adjust:
    :return:
    """
    will_adjust_count = pd_adjust.loc[(pd_adjust['drdays'] <= 10) &
                                      (pd_adjust['drdays'] >= 0) &
                                      (pd_adjust['adjust_remain_days'] == -1)]
    will_adjust_count = will_adjust_count.sort_values('readjust_dt')
    return will_adjust_count